package socket;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

/** 服务端 */
public class Server3 {
    private ServerSocket serverSocket;
    public Server3() {
        try {
            System.out.println("启动服务器中...");
            serverSocket = new ServerSocket(8088);
            System.out.println("服务端启动成功!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void start3(){
        try {
            while (true){
                Socket socket = serverSocket.accept();
                System.out.println("一个客户连接成功!");

                ClientHandler clientHandler = new ClientHandler(socket);
                Thread t = new Thread(clientHandler);
                t.start();

                ClientHandler1 clientHandler1 = new ClientHandler1(socket);
                Thread t1 = new Thread(clientHandler1);
                t1.start();

            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public class ClientHandler implements Runnable{
        private Socket socket;
        private String host;

        public ClientHandler(Socket socket) {
            this.socket = socket;
            //通过sockst获取远端计算机的IP地址的字符串格式
            host = socket.getInetAddress().getHostAddress();
        }

        public void run() {
            try {
                InputStream is = socket.getInputStream();//低级流
                InputStreamReader isr = new InputStreamReader(is, StandardCharsets.UTF_8);
                BufferedReader br = new BufferedReader(isr);

                String line;
                while ((line= br.readLine())!=null){
                    System.out.println(host+"说:"+line);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    public class ClientHandler1 implements Runnable{
        private Socket socket;

        public ClientHandler1(Socket socket) {
            this.socket = socket;
        }
        public void run() {
            try {
                OutputStream os = socket.getOutputStream();
                OutputStreamWriter osw = new OutputStreamWriter(os,StandardCharsets.UTF_8);
                BufferedWriter bw = new BufferedWriter(osw);
                PrintWriter pw = new PrintWriter(bw,true);

                Scanner sc = new Scanner(System.in);
                while (true){
                    String line1 = sc.nextLine();
                    pw.println(line1);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        Server3 server3 = new Server3();
        server3.start3();
    }
}
